 #pragma once
#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/time.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/stat.h>
#include<cstdio>
#include<cstring>
#include<fcntl.h>
#include<signal.h>
#include<pthread.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<vector>
#include<arpa/inet.h>
#include<sys/wait.h>
#include<functional>
#include <semaphore.h>
#include<jsoncpp/json/json.h>
#include<sys/select.h>
#include"Log.hpp"
#define Shm_User 1
#define Shm_Creater 2
#define SHM_SIZE 4096
#define SHM_PATH "./myfifo"
#define PATH_JD 0X66
using namespace std;

class Shm
{
public:
    Shm(int Id,int size=SHM_SIZE,string path=SHM_PATH)
    :id(Id),Shm_Size(size),Shm_Path(path)
    {
        key = ftok(Shm_Path.c_str(), PATH_JD);
        if (id == Shm_User)
        {
            shmid = shmget(key, Shm_Size, IPC_CREAT | 0666);
            if (shmid < 0)
                LOG(WARNING, "shmget error");
        }
        else
        {
            shmid = shmget(key, Shm_Size, IPC_CREAT |IPC_EXCL| 0666);
            if (shmid < 0)
                LOG(WARNING, "shmget error");
        }
        LOG(INFO,"crate 共享内存成功");
        shmaddr = shmat(shmid, nullptr, 0); // 第二个参数默认设为nullptr，第三个参数设为0即可
        LOG(INFO,"挂接共享内存成功");
    }
    void *Shm_Addr()
    {
        return shmaddr;
    }
    void Shm_Clean()
    {
        if(shmaddr!=nullptr)
        memset(shmaddr,0,Shm_Size);
    }
    ~Shm()
    {
        if (shmaddr != nullptr)
            shmdt(shmaddr);
        if (shmid >= 0&&id==Shm_Creater)
        {
            shmctl(shmid, IPC_RMID, nullptr);
        }
    }

private:
    int id;
    key_t key;
    void *shmaddr;
    int shmid;
    const int Shm_Size;
    string Shm_Path;
};